<?php

namespace App\Services\User;

use App\Constants\CodeData;
use App\Constants\VipType;
use App\Dao\AnchorEvaluateDataDao;
use App\Dao\AnchorVideoDao;
use App\Dao\AnchorVideoZanDao;
use App\Dao\AppUpgradeDao;
use App\Dao\AutoReplyDao;
use App\Dao\BannerDao;
use App\Dao\ClosenessDao;
use App\Dao\CommonSettingDao;
use App\Dao\FollowActionDao;
use App\Dao\FollowListDao;
use App\Dao\GiftDao;
use App\Dao\GreetMasterDao;
use App\Dao\MissionDao;
use App\Dao\PayCallDao;
use App\Dao\PhotoDao;
use App\Dao\UserDao;
use App\Dao\UserExtDao;
use App\Dao\UserLikeDao;
use App\Dao\UserVipDao;
use App\Exception\MessageException;
use App\Model\Anchor;
use App\Model\ChannelAgent;
use App\Model\CommonChange;
use App\Model\Filtration;
use App\Model\Guild;
use App\Model\LogScript;
use App\Model\Setting;
use App\Model\User;
use App\Model\UserCardPack;
use App\Model\UserCheckImgLog;
use App\Model\UserExt;
use App\Model\UserIdentity;
use App\Model\UserSign;
use App\Model\UserSignature;
use App\Services\Mission\MissionQueue;
use App\Utils\AliyunOssHelper;
use App\Utils\FunUtil;
use App\Utils\MemcacheClient;
use App\Utils\MongoDBClient;
use App\Utils\RedisClient;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use stdClass;
use function Hyperf\Config\config;
use function Hyperf\Translation\trans;

class UserService
{
    /**
     * Note - 获取去用户信息
     * DateTime 2024/7/16 10:59
     * User Admin
     * @param $userId
     * @param $language
     * @return array
     */
    public function userDetail($userId, $language)
    {
        $_interviewee = UserDao::getInstance()->findUserInfoCache($userId);
        $interviewee = array();
        if (!empty($_interviewee)) {
            //基本资料
            $interviewee['id'] = (int)$_interviewee['id'];
            $interviewee['nickname'] = $_interviewee['nickname'];
            $interviewee['head_image'] = $_interviewee['head_image'];
            $interviewee['sex'] = $_interviewee['sex'] == 1 ? trans('message.男', [], $language) : trans('message.女', [], $language);
            $interviewee['age'] = $_interviewee['age'];
            $interviewee['register_time'] = $_interviewee['register_time'];
            $interviewee['login_time'] = $_interviewee['login_time'];

            $interviewee['place'] = trim(str_replace('　', '', $_interviewee['province']) . " " . $_interviewee['city']);
            empty(trim($interviewee['place'])) && $interviewee['place'] = trans('message.保密', [], $language);

            $interviewee['origin_place'] = $_interviewee['origin_city'];
            empty(trim($interviewee['origin_place'])) && $interviewee['origin_place'] = trans('message.保密', [], $language);

            $interviewee['height'] = $_interviewee['height'] . 'cm';
            // $interviewee['income'] = $informationLang['income'][$_interviewee['income']]['name'];
            $interviewee['income'] = trans('information.income', [], $language)[$_interviewee['income']]['name'];
            $interviewee['marry'] = trans('information.income', [], $language)[$_interviewee['marry']]['name'];

            //详细资料
            $interviewee['education'] = $_interviewee['ext']->education;
            $interviewee['job'] = $_interviewee['ext']->job;
            $interviewee['constellation'] = $_interviewee['ext']->constellation;
            $interviewee['weight'] = $_interviewee['ext']->weight;
            $interviewee['birthday'] = $_interviewee['ext']->birthday;
            $interviewee['bust'] = $_interviewee['ext']->bust;

            $interviewee['noble'] = $_interviewee['noble'];
            $interviewee['channel'] = $_interviewee['channel'];
            $interviewee['super_noble'] = $_interviewee['super_noble'];
            $interviewee['signature'] = $_interviewee['signature'];//个性签名

            $interviewee['level'] = "1";

            $interviewee['is_cardAuth'] = $_interviewee['is_cardAuth'];
            $interviewee['is_faceAuth'] = $_interviewee['is_faceAuth'];
            $interviewee['real_education_status'] = 0;
            $interviewee['is_binding'] = $_interviewee['is_binding'];
            // $interviewee['show_gift'] = $_interviewee['show_gift'];
            $interviewee['show_gift'] = 0;
            // $interviewee['show_wealth'] = $_interviewee['show_wealth'];
            $interviewee['show_wealth'] = 0;

            $interviewee['video_price'] = 0;//视频价格
            $interviewee['audio_price'] = 0;

            if ($_interviewee['sex'] == 2) {
                //女用户
                $anchorInfo = Anchor::query()->where('uid', $userId)->first();
                if (!empty($anchorInfo) && $anchorInfo['status'] == 0) {
                    $interviewee['force_vip'] = $anchorInfo['force_vip'] ?? 0;
                    $interviewee['video_price'] = $anchorInfo['video_price'];
                    $interviewee['audio_price'] = $anchorInfo['audio_price'];   //语音通话固定价格30g/min
                    $interviewee['text_price'] = $anchorInfo['greet_price'];
                    $interviewee['wx_status'] = $anchorInfo['wx_status'];  // 0待审核，2审核不通过
                    // $interviewee['call_video'] = $anchorInfo['video_url'];
                    $interviewee['call_video'] = $anchorInfo['call_show_type'] == 1 ? $anchorInfo['call_show'] : '';
                    $interviewee['call_photo'] = $anchorInfo['call_show_type'] == 2 ? $anchorInfo['call_show'] : '';
                }
                $interviewee['work'] = $interviewee['job'];

                $interviewee['emotion'] = trans('information.marry', [], $language)[$_interviewee['marry']]['name'] ?: trans('message.保密', [], $language);

                $interviewee['weixin_price'] = new stdClass();
                $interviewee['check_weixin'] = 0;
                $interviewee['weixin'] = $_interviewee['weixin'];
                $interviewee['wx_new'] = $anchorInfo['wx_new'];
            }

            $interviewee["greet_time"] = 5;
        }
        return $interviewee;
    }


    /**
     * Note - 用户详情页接口
     * DateTime 2024/7/15 18:06
     * User Admin
     * @param $userInfo
     * @param $uid
     * @param $userId
     * @param $language
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws RedisException
     */
    public function getUserDetail($userInfo, $uid, $userId, $language): array
    {
        $interviewee = MemcacheClient::getInstance()->get('user_detail_info_' . $language . '_' . $userId);
        // list($mixLang, $sexLang, $informationLang) = importLanguageBag(['mix', 'sex', 'information'], $language);
        if ($interviewee === false) {
            $interviewee = $this->userDetail($userId, $language);
            MemcacheClient::getInstance()->set('user_detail_info_' . $language . '_' . $userId, $interviewee, 300);
        }

        // 微信号功能是否开启
        $interviewee['wx_show'] = CommonSettingDao::getWxSwitch($userInfo);

        if ($uid != $userId) {
            $interviewee['is_concern'] = FollowListDao::getInstance()->checkIsFans($uid, $userId) ? 1 : 0; //1表示当前用户已关注
        } else {
            $interviewee['is_concern'] = 2; //2表示不显示关注图标
        }

        $interviewee['online'] = UserDao::getInstance()->getUserOnlineStatus($userId);

        // 新人标识
        $interviewee['is_new_user'] = 0;
        if ($interviewee['register_time'] + 7 * 86400 >= time()) {
            $interviewee['is_new_user'] = 1;
        }


        $tmp_closeness = 0;
        if ($interviewee['sex'] == trans('message.女', [], $language)) {
            $uuid = $uid;
            $anchor_id = $userId;
        } else {
            $uuid = $userId;
            $anchor_id = $uid;
            $tmp_closeness = RedisClient::getInstance()->hGet("tmp_closeness:$uuid", $anchor_id) ?: 0;
        }

        $tease_arr = UserDao::getInstance()->readTease($userId, $uid);
        // 用户主页是否搭讪过
        $interviewee['is_tease'] = isset($tease_arr[$userId]) ? 1 : 0;
        // 用户亲密度
        $interviewee['closeness'] = ClosenessDao::read($uuid, $anchor_id) + $tmp_closeness;
        if ($interviewee['closeness'] > 0 || ($interviewee['sex'] == trans('message.男', [], $language) && $interviewee['login_time'] >= time() - 600)) {
            $interviewee['is_tease'] = 1;
        }

        // 判断oppo、vivo渠道不能被搭讪
        $ext_channel = User::query()->where(['id' => 1000001])->selectRaw("JSON_UNQUOTE(JSON_EXTRACT(ext2, '$.channel')) as channel")->value('channel');
        if (in_array($interviewee['channel'], ['xy_oppo', 'xy_vivo', 'xy_bd']) || in_array($ext_channel, ['xy_oppo', 'xy_vivo', 'xy_bd'])) {
            $interviewee['is_tease'] = 1;
        }

        $interviewee['closeness_level'] = ClosenessDao::getClosenessLevel($interviewee['closeness']);

        // 获取用户财富等级
        $wealth = User::query()->where('id', $userId)->value('wealth');
        $interviewee['wealth_level'] = getWealthLevel($wealth);

        $photo = PhotoDao::getInstance()->getList($userId);
        if (!empty($photo)) {
            $realHeadImg = AliyunOssHelper::compressImageHandle($interviewee['head_image'], 1000);
            array_unshift($photo, ['path' => $realHeadImg, 'is_recommend' => 0]);
        }

        //我的认证状态
        $Auth = (new UserIdentity())->getAuthInfo($interviewee, 0);
        $interviewee['head_image'] = AliyunOssHelper::compressImageHandle($interviewee['head_image'], 500);
        return formatData([
            'result' => 1,
            'msg' => $interviewee,
            'photos' => $photo,
            'auth' => $Auth
        ], 200, 200, '操作成功');
    }

    /**
     * Note - 用户详情页接口,其他数据(照片墙，礼物墙)
     * DateTime 2024/7/15 18:06
     * User Admin
     * @param mixed $user
     * @param mixed $uid
     * @param mixed $userId
     * @param mixed $language
     * @return array
     */
    public function getUserDetailOther(mixed $user, mixed $uid, mixed $userId, mixed $language)
    {
        $_interviewee = UserDao::getInstance()->findUserInfoCache($userId);
        if ($_interviewee['status'] != 0) {
            throw new MessageException('用户被封禁！', 200, ['result' => 4]);
        }
        $gift = array();
        $evaluate = array();
        if (!empty($_interviewee)) {
            if ($_interviewee['sex'] == 2) {
                $gift = GiftDao::getInstance()->getGiftByUid($userId, 2, 5);
                //主播形象
                $evaluateDataDao = new AnchorEvaluateDataDao();
                $evaluate = $evaluateDataDao->getEvaluateByAnchor($userId, $language);

                foreach ($evaluate as &$item) {
                    if (empty($item['bg_color'])) {
                        $str = substr($item['color'], 1, strlen($item['color']));
                        $arr = str_split($str, 2);
                        $new = "#";
                        foreach ($arr as $k => $a) {
                            $aa = bcadd(base_convert($a, 16, 10), 80);
                            if ($aa > 255) {
                                $aa = 255;
                            }
                            $new .= base_convert($aa, 10, 16);
                        }
                        $item['bg_color'] = $new;
                    }
                }
            } else {
                // 男用户送出的礼物
                $gift = GiftDao::getInstance()->getGiftByUid($userId, 1, 5);
            }

            //增加访问记录
            FollowActionDao::getInstance()->addVisit($uid, $userId);

        }

        return formatData(array('result' => 1, 'gift' => $gift, 'evaluate' => $evaluate), 200, 200, '操作成功');
    }


    /**
     * Note - 获取相册列表,并判断是否被VIP用户查看
     * DateTime 2024/7/16 12:18
     * User Admin
     * @param $userInfo
     * @param $userId
     * @param $type
     * @param $page
     * @param $pageSize
     * @param $from
     * @param $version_code
     * @param $channel
     * @return array
     */
    public function getUserPhotos($userInfo, $userId, $type, $page, $pageSize, $from, $version_code, $channel)
    {
        $list = PhotoDao::getInstance()->getUserPhotos($userId, $type, $page, $pageSize, $from, $version_code, $channel);
        // 用户是否查看照片记录
        $check_data = [];
        if (($userInfo["super_noble"] == 1 || $userInfo["noble"] == 1)) {
            $ids = array_column($list, "id");
            $check_data = UserCheckImgLog::query()->where('uid', $userInfo['id'])->where('type', 0)->whereIn('resource_id', $ids)->get()->toArray();

            $check_data = array_column($check_data, null, 'resource_id');
        }

        // vip用户是否查看私密照片
        foreach ($list as &$val) {
            if (isset($check_data[$val['id']])) {
                $val['is_check'] = 1;
            } else {
                $val['is_check'] = 0;
            }

            $val['path'] = AliyunOssHelper::compressImageHandle($val['path'], 1000);
            $val['thumb'] = AliyunOssHelper::compressImageHandle($val['thumb'], 500);
        }
        return formatData(['result' => 1, 'msg' => $list], 200, 200, '操作成功');
        // \Tool::JSON(200, ['result' => 1, 'msg' => $list]);
    }

    /**
     * Note - 获取视频列表
     * DateTime 2024/8/16 15:07
     * User Admin
     * @param $userInfo
     * @param $userId
     * @param $type
     * @param $page
     * @param $pageSize
     * @param $from
     * @param $version_code
     * @param $channel
     * @return array
     */
    public function getUserVideos($userInfo, $userId, $type, $page, $pageSize, $from, $version_code, $channel)
    {
        $list = AnchorVideoDao::getInstance()->getAllVideo($userId, $type, $page, $pageSize, $from, $version_code, $channel);

        // 用户是否查看视频记录
        $check_data = [];
        if (($userInfo["super_noble"] == 1 || $userInfo["noble"] == 1)) {
            $ids = array_column($list, "id");
            $check_data = UserCheckImgLog::query()->where('uid', $userInfo['id'])->where('type', 1)->whereIn('resource_id', $ids)->get()->toArray();
            $check_data = array_column($check_data, null, 'resource_id');
        }

        $anchorVideoZanDao = AnchorVideoZanDao::getInstance();
        foreach ($list as &$v) {
            if (empty($v['first_photo'])) {
                $v['first_photo'] = $v['url'] . "?x-oss-process=video/snapshot,t_0,m_fast,ar_auto";
            }
            $v['click'] = $anchorVideoZanDao->zanCount($v['id']);
            $v['is_click'] = $anchorVideoZanDao->isZan($userInfo['id'], $v['id']);

            // vip用户是否查看私密视频
            if (isset($check_data[$v['id']])) {
                $v['is_check'] = 1;
            } else {
                $v['is_check'] = 0;
            }
        }

        return formatData(['result' => 1, 'msg' => $list], 200, 200, '操作成功');
        // \Tool::JSON(200, ['result' => 1, 'msg' => $list]);
    }

    public function getAboutFriendList($uid)
    {
        $res = UserExtDao::getInstance()->getSpaceInfoMemcache($uid);
        $retval = array();
        if (!empty($res)) {
            //征友条件
            $retval['want_age'] = $res['want_age'];
            $retval['want_place'] = $res['want_place'];
            $retval['want_height'] = $res['want_height'];
            $retval['want_weight'] = $res['want_weight'];
            $retval['want_education'] = (int)$res['want_education'];
            $retval['want_income'] = (int)$res['want_income'];
        }
        return formatData(['result' => 1, 'msg' => $retval], 200, 200, '操作成功');
    }

    public function editAboutFriend($uid, $params)
    {
        $data = array();

        $data['want_age'] = $params['want_age']; //如："23|26"
        $data['want_place'] = $params['want_place']; //如："山西|太原"
        $data['want_height'] = $params['want_height']; //如："165|175"
        $data['want_education'] = intval($params['want_education']); // 如 1
        $data['want_income'] = intval($params['want_income']); // 如 2
        $data['want_weight'] = intval($params['want_weight']); // 体重

        $exist = UserExtDao::getInstance()->userExtExist($uid);
        if ($exist) {
            $retval = UserExt::where('uid', $uid)->update($data);
        } else {
            $data['uid'] = $uid;
            $retval = UserExt::query()->insert($data);
        }

        if ($retval) {
            MemcacheClient::getInstance()->delete("user_spaceinfo_condition_" . $uid);
            return formatData(array('result' => 1), 200, 200, '修改资料成功');
        }
        return formatData(array('result' => 0), 500, 500, '修改失败');

    }

    /**
     * Note - 主播自动打招呼:弹窗提醒+发送打招呼模板，打招呼模板不存在，则随机获取一条自动回复消息发送
     * DateTime 2024/7/17 16:04
     * User Admin
     * @param $userInfo
     * @param array $all
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function anchorGreet($userInfo, array $all)
    {
        $version_code = $all['version_code'];
        $channel = $all['channel'];
        $from = $all['from'];
        $uid = $userInfo['id'];
        $anchor_id = $all['anchor_id'];
        $language = $all['language'] ?? 'en';

        if ($version_code > 107) {
            $text = trans("看我那么久，喜欢我吗？要不来聊聊", [], $language);
            $insert_data = [
                "uid" => $uid,
                "anchor_id" => $anchor_id,
                "script_id" => 0,
                "content" => $text,
                "script_type" => 6,
                "action_reply" => 0,
                "ctime" => time(),
                "date_string" => date("Y-m-d"),
                "time_string" => date("Y-m-d H:i:s"),
            ];
            $greet_id = LogScript::insertGetId($insert_data);

            $cb['result'] = 1;
            $cb['msg'] = [
                "greet_id" => $greet_id,
                'auto_call_time' => 5,
                'bubble_disappear_time' => 7,
                'tip_desc' => $text
            ];
            return formatData($cb);
        }

        if ((new AppUpgradeDao())->isHideRobotChat($from, $version_code, $channel)) {
            throw new MessageException("机器人私聊功能已关闭", CodeData::NO_PROMPT);
        }

        if ($userInfo['sex'] != 1) {
            throw new MessageException("男用户才调用", CodeData::NO_PROMPT);
        }

        $inAudit = UserDao::getInstance()->inAudit($uid);
        if ($inAudit) {
            throw new MessageException("审核环境注册用户", CodeData::NO_PROMPT);
        }

        $anchor = User::where('id', $anchor_id)->first();
        $anchor = modelToArray($anchor);

        if ($anchor['sex'] != 2) {
            throw new MessageException("男用户查看女主播才调用", CodeData::NO_PROMPT);
        }
        $online = $anchor['online'];
        if ($online != 1) {
            throw new MessageException("主播不在线", CodeData::NO_PROMPT);
        }

        $mongo = MongoDBClient::getInstance();
        $where1 = ['uid' => $uid, 'receive_uid' => $anchor_id];
        $b1 = !empty($mongo->find('tb_user_chat_v2', $where1));

        $where2 = ['uid' => $anchor_id, 'receive_uid' => $uid];
        $b2 = !empty($mongo->find('tb_user_chat_v2', $where2));
        if ($b1 || $b2) {
            throw new MessageException("发送过消息", CodeData::NO_PROMPT);
        }

        // 随机获取打招呼模板
        $result = GreetMasterDao::getInstance()->getRandOne($anchor_id);
        if (empty($result)) {
            // 记录脚本推送历史
            [$script_id, $content] = AutoReplyDao::getInstance()->getReplyContentWithId($anchor_id, 3, $language);
            $imageUrl = PhotoDao::getInstance()->getFemalePhotoPath($anchor_id);
            $script_type = 4;
        } else {
            [$script_id, $content, $imageUrl, $audioUrl, $audioLen] = [$result["id"], $result["text"], $result["image_url"], $result["audio_url"], $result["audio_len"]];
            $script_id = -$script_id;
            $script_type = 5;
        }

        $insert_data = [
            "uid" => $uid,
            "anchor_id" => $anchor_id,
            "script_id" => $script_id,
            "content" => $content,
            "script_type" => $script_type,
            "action_reply" => 0,
            "ctime" => time(),
            "date_string" => date("Y-m-d"),
            "time_string" => date("Y-m-d H:i:s"),
        ];
        $greet_id = LogScript::insertGetId($insert_data);

        //发送文本
        // $rs = (new WyyClient())->putSendMsgQueue($anchor_id, $uid, $content, 1, 3);
        //发送图片
        // if ($imageUrl) {
        //     $rs = (new \WyyClient())->putSendMsgQueue($anchor_id, $uid, $imageUrl, 3, 3);
        // }
        //发送语音
        // if ($audioUrl) {
        //     $rs = (new \WyyClient())->putSendMsgQueue($anchor_id, $uid, $audioUrl, 2, 3, $audioLen);
        // }
        $cb['result'] = 1;
        $cb['msg'] = compact("greet_id");
        return formatData($cb);
        // Tool::JSON(200, $cb, "success");
    }

    /**
     * Note - 获取用户基础信息
     * DateTime 2024/7/17 16:04
     * User Admin
     * @param mixed $user
     * @param $userId
     * @param $language
     * @return array
     */
    public function getBaseInfo(mixed $user, $userId, $fromPage, $language)
    {
        $uid = $user['id'];
        $tmp_closeness = 0;
        if ($user['sex'] == 1) {
            $uuid = $uid;
            $anchor_id = $userId;
            $tmp_closeness = RedisClient::getInstance()->hGet("tmp_closeness:{$uuid}", $anchor_id) ?: 0;
        } else {
            $uuid = $userId;
            $anchor_id = $uid;
        }

        $userInfo = UserDao::getInstance()->findBaseInfo($userId);

        if ($userInfo['status'] != 0) {
            if ($fromPage == 1){
                throw new MessageException("该用户被封禁", CodeData::NO_PROMPT, ['result' => 4]);
            }
            throw new MessageException("用户被封禁", CodeData::NEED_TIPS, ['result' => 4]);
        }

        if ($userInfo['isdel'] == 1) {
            if ($fromPage == 1){
                throw new MessageException("该账户已注销", CodeData::NO_PROMPT, ['result' => 4]);
            }
            throw new MessageException("该账户已注销", CodeData::NEED_TIPS, ['result' => 4]);
        }

        $userInfo['auth'] = [
            'real_card_status' => $userInfo['is_cardAuth'],
            'real_img_status' => $userInfo['is_faceAuth'] == 3 ? 1 : $userInfo['is_faceAuth'],
            'real_education_status' => 0,
            'is_binding_phone' => $userInfo['is_binding']
        ];
        $userInfo['ext'] = !empty($userInfo['ext']) ? json_decode($userInfo['ext'], true) : '';
        $userInfo['job'] = isset($userInfo['ext']['job']) ? trans('information.job', [], $language)[$userInfo['ext']['job']]['name'] : trans('message.保密', [], $language);
        $userInfo['constellation'] = isset($userInfo['ext']['constellation']) ? trans('constellation.' . $userInfo['ext']['constellation'], [], $language) : '';

        $userInfo['weight'] = isset($userInfo['ext']['weight']) && (string)$userInfo['ext']['weight'] != "" ? $userInfo['ext']['weight'] : '60';

        $userInfo['is_mutual'] = FollowListDao::getInstance()->isMutual($uid, $userId);
        $userInfo['is_concern'] = FollowListDao::getInstance()->isConcern($uid, $userId);
        $userInfo['photos'] = PhotoDao::getInstance()->getList($userId);

        $userInfo['force_vip'] = $userInfo['force_vip'] ?: 0;

        $userInfo['closeness'] = ClosenessDao::read($uuid, $anchor_id) + $tmp_closeness;
        $userInfo['closeness_level'] = ClosenessDao::getClosenessLevel($userInfo['closeness']);

        $signArr = trans('slogan', [], $language);
        if (empty($userInfo['signature'])) {
            $userInfo['signature'] = $signArr[array_rand($signArr)];
        }

        $userInfo['is_like'] = UserLikeDao::getInstance()->checkUserLike($uuid, $anchor_id);

        // 重置昵称后id一样，发不出去信息
        if (!empty($user['nickname_new']) && $user['nickname_new'] != $user['id']) {
            $userInfo['reset_name'] = '1';
        } else if ($user['nickname'] != $user['id']) {
            $userInfo['reset_name'] = '1';
        } else {
            $userInfo['reset_name'] = '0';
        }

        $userInfo['is_new_user'] = 0;
        if ($userInfo['register_time'] + 7 * 86400 >= time()) {
            $userInfo['is_new_user'] = 1;
        }

        $userInfo['textFee'] = bcmul($userInfo['text_price'], 0.4, 2);

        unset($userInfo['ext'], $userInfo['is_cardAuth'], $userInfo['is_faceAuth'], $userInfo['is_binding']);
        return formatData(['result' => 1, 'msg' => $userInfo]);

    }


    /**
     * Note - 获取用户关系亲密度数据接口
     * DateTime 2024/7/18 16:41
     * User Admin
     * @param mixed $user
     * @param $userId
     * @param $language
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws RedisException
     */
    public function getCloseness(mixed $user, $userId, $language)
    {
        $uid = $user['id'];
        $tmp_closeness = 0;
        if ($user['sex'] == 1) {
            $uuid = $uid;
            $anchor_id = $userId;
            $tmp_closeness = RedisClient::getInstance()->hGet("tmp_closeness:{$uuid}", $anchor_id) ?: 0;
        } else {
            $uuid = $userId;
            $anchor_id = $uid;
        }

        $closeness = ClosenessDao::read($uuid, $anchor_id) + $tmp_closeness;
        $closeness_param = CommonSettingDao::getInstance()->getList("CLOSENESS_PARAM");
        $param = json_decode($closeness_param['value'], true);
        // list($mixLang) = importLanguageBag(['mix'], $_REQUEST['language'] ?? 'en');
        $level = 0;
        foreach ($param as &$item) {
            $item['remark'] = trans('message.' . $item['remark'], [], $language);
            if ($item['score'] <= $closeness) {
                $item['unlock'] = 1;
                $level = $item['level'];
            } else {
                $item['unlock'] = 0;
            }
        }

        return formatData(['result' => 1, 'closeness' => $closeness, 'level' => $level, 'msg' => $param]);
    }


    /**
     * Note - 修改用户信息
     * DateTime 2024/8/2 18:24
     * User Admin
     * @param mixed $user
     */
    public function editInfo(mixed $user, $data)
    {
        $uid = $user["id"];
        $filtrationModel = new Filtration();
        $missionFlag = 0;
        if (isset($data['phone']) && $user['is_binding'] == 1 && $user['phone'] != $data['phone']) {
            // \Tool::JSON(\CodeData::NEED_TIPS, '', '你已经绑定过手机了，无法修改');
            return formatData(['result' => 0], 200, CodeData::NEED_TIPS, '你已经绑定过手机了，无法修改');
        }

        //昵称敏感词检测
        if ($filtrationModel->isExistIllega($data['nickname'])) {
            // \Tool::JSON(\CodeData::NEED_TIPS, array('result' => 0), '昵称含有敏感词哦');
            return formatData(['result' => 0], 200, CodeData::NEED_TIPS, '昵称含有敏感词哦');
        }

        //昵称长度检测
        if (mb_strlen($data['nickname'], 'utf8') > 64) {
            // \Tool::JSON(\CodeData::NEED_TIPS, array('result' => 0), '昵称最长不得超过64个字符');
            return formatData(['result' => 0], 200, CodeData::NEED_TIPS, '昵称最长不得超过64个字符');
        }

        // 昵称不能是纯数字
        $simplyNickname = str_replace(' ', '', $data['nickname']);
        if (is_numeric($simplyNickname)) {
            return formatData(['result' => 0], 200, CodeData::NEED_TIPS, '昵称不能是纯数字');
        }

        //昵称检测是否重复
        // $check_nick = $userModel->find('id', 'nickname = ? and id != ?', array($data['nickname'], $uid));
        $exists = User::query()->where('nickname', $data['nickname'])->where('id', '<>', $uid)->exists();
        if ($exists) {
            // \Tool::JSON(\CodeData::NEED_TIPS, '', '昵称已存在，请换一个试试');
            return formatData(['result' => 0], 200, CodeData::NEED_TIPS, '昵称已被使用');
        }

        //个人签名长度检测
        if (mb_strlen($data['signature'], 'utf8') > 150) {
            // \Tool::JSON(\CodeData::NEED_TIPS, array('result' => 0), '个人签名最长不得超过150个字符');
            return formatData(['result' => 0], 200, CodeData::NEED_TIPS, '个人签名最长不得超过150个字符');
        }


        if (isset($data['signature']) && $data['signature'] != "" && $data['signature'] != $user['signature']) {
            $signature_audit['uid'] = $uid;
            $signature_audit['signature'] = $data['signature'];
            $signature_audit['signature_old'] = $user['signature'];
            $signature_audit['suggestion'] = 0;
            $signature_audit['status'] = 0;
            $signature_audit['create_time'] = date("Y-m-d H:i:s");

            $signAuditModel = new UserSignature();
            $signAuditModel->newQuery()->updateOrInsert(['uid' => $uid], $signature_audit);
            // if (!$signAuditModel->find("uid", "uid=?", [$uid])) {
            //     $signAuditModel->newQuery()->insert($signature_audit);
            // } else {
            //     $signAuditModel->newQuery()->where("uid", $uid)->update($signature_audit);
            // }
            //个性签名任务取消
            //$missionFlag |= 8;
            //\MissionMgr::signature($uid, $user['sex']);
        }

        if (isset($data['head_image']) && $data['head_image'] != "" && AliyunOssHelper::delCompressImageParam($data['head_image']) != AliyunOssHelper::delCompressImageParam($user['head_image_new'])) {
            $data['head_image_status'] = 3;
            $data['head_image_new'] = $data['head_image'];
            $data['head_image_time'] = time();
            unset($data['head_image']);
        }

        if (isset($data['education']) || isset($data['job']) || isset($data['birthday']) || isset($data['weight']) || isset($data['bust'])) {
            !is_object($user['ext']) && $user['ext'] = (object)$user['ext'];
            if (!empty($data['education'])) {
                $user['ext']->education = $data['education'];
            }
            if (!empty($data['job'])) {
                $user['ext']->job = $data['job'];
            }
            if (!empty($data['weight'])) {
                $user['ext']->weight = $data['weight'];
            }
            if (!empty($data['bust'])) {
                $user['ext']->bust = $data['bust'];
            }

            if (!empty($data['birthday'])) {
                $user['ext']->birthday = $data['birthday'];
                $data['age'] = FunUtil::birthday($data['birthday']);
                $user['ext']->constellation = FunUtil::constellation($data['birthday']);
            }
            $data['ext'] = json_encode($user['ext'], JSON_UNESCAPED_UNICODE);
            unset($data['education'], $data['job'], $data['birthday'], $data['bust']);
        }
        $data['weight'] = intval($data['weight']);
        if (!empty($data['origin_province'])) {
            $missionFlag |= 2;
        }

        $data["isNewAudit"] = 0;
        $data["update_time"] = date("Y-m-d H:i:s");
        // $rs = $userModel->updateV2($uid, $data);
        $rs = User::query()->where('id', $uid)->update($data);

        if (!$rs) {
            // \Tool::JSON(\CodeData::NEED_TIPS, '', '修改失败');
            return formatData(['result' => 0], 200, CodeData::NEED_TIPS, '修改失败');
        }

        if ($missionFlag > 0) {
            MissionQueue::profile($uid, $missionFlag);
        }

        MemcacheClient::getInstance()->delete("userInfo_" . $uid);
        $language = Context::get('language') ?? 'en';
        MemcacheClient::getInstance()->delete('user_detail_info_' . $language . $uid);
        $user = UserDao::getInstance()->findUserInfoCache($uid);
        // \Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $user), '修改资料成功');
        return formatData(['result' => 1, 'msg' => $user]);

    }


    /**
     * Note - 完善个人资料+绑定公会+设置收费
     * DateTime 2024/8/7 16:35
     * User Admin
     * @param $uid
     * @param $data
     * @return array
     */
    public function perfect($uid, $data)
    {
        logInfo("perfect_data", $data);
        $user = User::findUserInfoById($uid);
        // 0：正常用户  1：已删除用户 2：未完善资料用户
        if ($user['isdel'] != 2) {
            // return formatData('', 200, CodeData::NEED_TIPS,'未完善资料的用户才可以修改');
            throw new MessageException('未完善资料的用户才可以修改');
        }

        //过滤昵称
        $nickname = str_replace(array('\n', '\s', '\t', '\v', '\r', '\f', ':::'), "", $data['nickname']);
        if ((new Filtration())->isExistIllega($nickname)) {
            // return formatData('', 200, CodeData::NEED_TIPS,'昵称不合规');
            throw new MessageException('昵称不合规');
        }

        $simplyNickname = str_replace(' ', '', $nickname);
        if (is_numeric($simplyNickname)) {
            throw new MessageException('昵称不能全为数字');
            // return formatData('', 200, CodeData::NEED_TIPS,'昵称不能全为数字');
        }

        $head_image = $head_image_new = $data['head_image'] ?? '';
        if (empty($head_image)) {
            if ($data['sex'] == 2) {
                $head_image = $head_image_new = config('custom.woman_headimg');
            } else {
                $head_image = $head_image_new = config('custom.man_headimg');
            }
        }

        $update = [
            'sex' => intval($data['sex']) ?: 1,
            'isdel' => 0,
            'nickname' => $nickname,
            'nickname_new' => $nickname,
            'nickname_new_status' => 3,
            'nickname_suggestion' => 0,
            'head_image' => $head_image,
            'head_image_new' => $head_image_new,
            'head_image_status' => empty($head_image_new) ? 0 : 1,
            'isNewAudit' => 1, //头像、昵称初审
            'update_time' => date("Y-m-d H:i:s"),
            'online' => 1,
        ];

        if (!empty($head_image_new)) {
            if ($head_image_new != config('custom.man_headimg') && $head_image_new != config('custom.woman_headimg')) { // 不是默认头像
                $update['head_image_time'] = time();
            }
            $update['head_image_status'] = 3;

        }

        if (empty($user['channel'])) {
            $update['channel'] = $data['channel'];
        }
        $guildModel = new Guild();
        // 判断 inviteUid 是否是公会
        if (!empty($data['inviteUid'])) {
            $guild = $guildModel->newQuery()->where('guild_num', $data['inviteUid'])->first();
            if ($update['sex'] == 2 && !empty($guild)) {
                $update['guild_num'] = $data['guild_num'];
                $user['guild_num'] = $data['guild_num'];
                $update['push_level'] = 2; //拥有邀请码进入的女用户为女嘉宾等级
            } else {
                // 代理渠道绑定
                $channelAgent = ChannelAgent::query()->where('status', 1)->where('channel_number', $data['inviteUid'])->first();
                if (!empty($channelAgent)) {
                    ChannelAgent::query()->insertOrIgnore([
                        'uid' => $uid,
                        'channel_num' => $data['inviteUid'],
                        'ctime' => time()
                    ]);
                    $update['agent_num'] = $data['inviteUid'];
                }
            }
        }
        // 用户有上级邀请人，记录绑定时间
        if (!empty($update['inviteUid']) || !empty($update['guild_num']) || !empty($update['agent_num'])) {
            $now_time = time();
            $update['ext2'] = DB::raw("json_set(ext2, '$.bind_time', {$now_time})");
        }
        $res = User::query()->where('id', $user['id'])->update($update);
        if ($res) {
            $this->setPrice($user['id'], $user['guild_num'], $update['sex']);
            if ($user['is_audit'] != 1 && $update['sex'] != 1) {
                $this->newUserMsg($user['id']);
            }
            MemcacheClient::getInstance()->delete("userInfo_" . $uid);
            return array_merge($user, $update);
        }
        return [];

    }

    /**
     * Note - 系统自动推送新用户消息
     * DateTime 2024/8/7 18:12
     * User Admin
     * @param $uid
     */
    public function newUserMsg($uid)
    {
        $content = "寻缘新用户福利：
1、可在新人活动里领取30金币+视频卡（免费通话一分钟）；新人活动能领取三天，每天奖励都不一样，记得领取哟~
2、动态页面签到可每天领取金币，快来签到吧~
3、我的任务完成任务获取金币；新手任务可完善资料、上传头像、发布动态、每日任务等都能获得金币，快来完成任务啦~
";
        $data['content'] = "$content";
        $data['content_type'] = 1;
        FunUtil::socket_client('assistant_uid', $uid, '', $data);

        $content = "寻缘平台温馨提示：
1.请用户根据自身实际情况理性消费、合理消费，切勿冲动消费。
2.平台女性用户均通过真人认证，不存在机器人，请放心体验。如发现对方使用脚本搭讪和回复，请立即举报。
3.有些网络骗子会以兼职刷单等形式欺骗缴纳保证金，请擦亮眼睛，切勿相信。
4.谎称小礼物可解锁微信，送大礼物可私下见面甚至发生关系多属欺骗行为，请谨慎辨别。
5.警惕酒托、茶托、饭托，发现色情招嫖、骚扰广告等信息请及时举报。
6.如遇到疑似诈骗的用户及行为，请立即举报，平台客服将在24小时内受理。
7.更多防诈技巧请查看平台《防诈骗指南》，提高安全防范意识。
任何声称自己是平台客服、工作人员表示转账可以获取联系方式、安排线下见面、转账返现、转账送福利都是欺骗行为，请立即举报。
";
        $data['content'] = "$content";
        $data['content_type'] = 1;
        FunUtil::socket_client('assistant_uid', $uid, '', $data);
    }


    /**
     * Note - 设置主播通话价格
     * DateTime 2024/8/7 18:08
     * User Admin
     * @param $uid
     * @param $guildNum
     * @param $sex
     */
    public function setPrice($uid, $guildNum, $sex)
    {
        if ($sex == 2) {
            $anchorData = [
                'uid' => $uid,
                'ctime' => time(),
                'work' => '保密',
                'rate' => '0.4',
                'emotion' => '保密',
                'guild_num' => $guildNum,
                'video_price' => config('custom.video_price'),
                'audio_price' => config('custom.audio_price'),
                'greet_price' => config('custom.greet_price')
            ];
            Anchor::query()->insert($anchorData);
            MemcacheClient::getInstance()->delete("userInfo_" . $uid);
        }
    }


    /**
     * 我的(个人中心数据)
     * @param $user
     * @param $params
     * @return array
     */
    public function getUserInfo($user, $params)
    {
        $uid = $user['id'];
        $language = Context::get('language', 'en');
        $followDao = FollowListDao::getInstance();
        // 粉丝数
        $fan = $followDao->getUserFansNum($uid);
        // 关注数
        $mutual = $followDao->getMutualNum($uid);
        // 互粉数
        $focus = $followDao->getUserFocusNum($uid);
        $follow_number = compact('fan', "mutual", "focus");

        // 我的页面菜单展示配置
        $setting = Setting::query()->select('my_function_status', 'user_sign_switch')->first();
        $my_function_status = $setting['my_function_status'];
        $user_sign_switch = $setting['user_sign_switch'];
        $function = json_decode($my_function_status, true);

        // $goddess_rank = ($user['sex'] == 2) ? 1 : 0;
        // if ($goddess_rank > 0) {
        //     $sql = "SELECT value FROM tb_common_change WHERE uniq='rank' AND version_code<={$user['version_code']} LIMIT 1";
        //     $goddess_rank = intval($followModel->findOneField($sql, 'value', 0));
        // }
        if ($user['sex'] == 2) {
            $goddess_rank = CommonChange::query()->where('uniq', 'rank')->where('version_code', '<=', $user['version_code'])->value('value');
            $function_status = $function['woman'];
        } else {
            $goddess_rank = 0;
            $function_status = $function['man'];
        }

        // 今天是否签到
        $sign_exists = UserSign::query()->where('uid', $uid)->where('sign_last_date', date('Y-m-d'))->exists();
        $task = [
            'user_sign_switch' => intval($user_sign_switch),
            'is_sign_today' => $sign_exists ? 1 : 0,
        ];

        $banner = BannerDao::getInstance()->getOnlineList(1, $user['version_code'], 1, $user, $params['package'] ?? '', 5, $goddess_rank);
        $user['goddess_rank'] = '';

        if ($goddess_rank > 0) {
            foreach ($banner as $v) {
                if ($v['title'] == '女神排行榜') {
                    $user['goddess_rank'] = base64_decode($v['link']);
                    break;
                }
            }
        }

        $vipInfo['type'] = 0;
        //VIP信息：类型、有效日期
        if ($user["noble"] == 1 || $user["super_noble"] == 1) {
            $vipType = $user["super_noble"] == 1 ? 2 : 1;
            $vipInfo['type'] = $vipType;
            $vipData = UserVipDao::getInstance()->getVipInfo($vipType, $uid);
            $vipInfo['endtime'] = $vipData['etime'];
            $vipInfo['subtype'] = VipType::getVipTypeInfo($vipData['type']);

            // 是会员判断是否是体验
            $vipInfo['is_trial'] = 0;
            // $card = $followModel->findOne("select id,use_time from tb_user_card_pack where uid=$uid and status = 3 and card_type=3");
            $card = UserCardPack::query()->select('id', 'use_time')
                ->where('uid', $uid)->where('status', 3)->where('card_type', 3)->first();
            if (!empty($card)) {
                $trial_num = CommonSettingDao::getValue('trial_vip_card');// VIP体验卡体验天数
                if ($card['use_time'] + $trial_num * 86400 <= time()) {
                    // $followModel->update($card['id'], ['status' => 1, 'extend' => time()], "tb_user_card_pack");
                    // VIP体验卡体验天数到期
                    UserCardPack::query()->where('id', $card['id'])->update(['status' => 1, 'extend' => time()]);
                } else {
                    $vipInfo['is_trial'] = 1;
                }
            }
        }

        // 用户聊天托管
        // $auto_reply_status = Anchor::query()->where('uid', $uid)->value('auto_reply_status') ?? 0;
        $auto_reply_status = $user['auto_reply_status'] ?? 0;

        // 用户签名
        $signature = UserSignature::query()->where('uid', $uid)->where('status', 0)->value('signature');

        $user["signature"] = $signature ?? $user["signature"];
        // 用户是否被禁言
        $user["isForbid"] = (int)FunUtil::gagUserChat($uid);

        // 封面类型：1-视频，2-图片
        $call_show_type = $user['call_show_type'] ?? 0;
        if ($call_show_type == 1) {
            $user['video_url'] = $user['call_show'];
            $user['photo_url'] = '';
        } elseif ($call_show_type == 2) {
            $user['video_url'] = '';
            $user['photo_url'] = $user['call_show'];
        } else {
            $user['video_url'] = '';
            $user['photo_url'] = '';
        }

        // 用户通话可用金币数 用户前端判断
        $user['call_gold'] = $user['gift_count'] + $user['sys_send_count'] + $user['recharge_send_count'];

        // 获取用户财富等级
        $user['wealth_level'] = getWealthLevel($user['wealth']);

        // 新人标识
        $user['is_new_user'] = 0;
        if ($user['register_time'] + 7 * 86400 >= time()) {
            $user['is_new_user'] = 1;
        }

        $user['wx_show'] = CommonSettingDao::getWxSwitch($user);; // 是否开启微信功能
        if ($user["sex"] == 2) {
            $wx_setting = CommonSettingDao::getJsonValue("USER_WX_SETTING");

            $user['wx_set_price'] = $wx_setting['user_set_price'] ?? '0';

            // $sql = "SELECT rate FROM tb_anchor WHERE `uid`=$uid LIMIT 1";
            // $rate = $followModel->findOneField($sql, 'rate');
            $user["videoFee"] = $user["video_price"] * $user['rate'];
            $user["audioFee"] = $user['audio_price'] * $user['rate'];
            $user["textFee"] = $user['text_price'] * $user['rate'];
        }

        // 回复消息获得收益开关
        $user['reply_msg_income'] = CommonSettingDao::getValue('REPLY_INCOME');

        $quick_chat_count = 0;
        if (!$user['noble'] || !$user['super_noble']) {
            $quick_chat_count = PayCallDao::getInstance()->getFreeVideoCount($uid);
        }

        // 获取代理余额
        // $guild_balance = $followModel->findOneField("select account from tb_guild where uid = {$uid}","account") ?: 0;
        $guild_balance = 0;
        $user['integrate_usable_count'] = bcadd($user['integrate_usable_count'], $guild_balance, 2);

        if ($user['integrate_usable_count'] < 0) {
            $user['integrate_freeze_count'] = bcadd($user['integrate_freeze_count'], $user['integrate_usable_count'], 2);
            $user['integrate_usable_count'] = 0;
        }

        $user['is_referrer'] = 0;    // 是否超推
        // $guild = $followModel->find("id", "uid = ? and status = 1", [$uid], "", 'tb_guild');
        $exists = Guild::query()->where('id', $uid)->where('status', 1)->exists();
        if ($exists) {
            $user['is_referrer'] = 1;
        }

        $mission = MissionDao::getInstance()->getUserMissionInfo($uid, $user['sex'], $language);

        $user['head_image'] = AliyunOssHelper::compressImageHandle($user['head_image'] ?? '', 1000); // 压缩头像背景图

        // \Tool::JSON(\CodeData::SUCCESS, ['result' => 1, 'msg' => compact('user', 'task', 'follow_number', 'banner', 'function_status', 'auto_reply_status', 'vipInfo', 'quick_chat_count', 'mission')]);
        return formatData([
            'result' => 1,
            'msg' => [
                'user' => $user,
                'task' => $task,
                'follow_number' => $follow_number,
                'banner' => $banner,
                'function_status' => $function_status,
                'auto_reply_status' => $auto_reply_status,
                'vipInfo' => $vipInfo,
                'quick_chat_count' => $quick_chat_count,
                'mission' => $mission,
            ]
        ]);

    }


}